/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program.gui;

import java.awt.Color;
import java.awt.Desktop;
import java.io.File;
import java.sql.Timestamp;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.TableColumn;
import program.beans.Bill;
import program.bl.BillController;
import program.gui.model.ViewBillTableModel;
import program.gui.model.ViewBillTableRenderer;
import program.properties.PropertyManager;
import program.utilities.DateUtilities;

/**
 * A Frame where all bills within a specified period are shown
 *
 * Responsible: Patrick, Bernhard
 */
public class MainFrame extends javax.swing.JFrame {

    private BillController billController = BillController.getInstance();
    private ViewBillTableModel vbtm;

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        setSize(1000, 600);
        setLocationRelativeTo(null);
        try {
            vbtm = new ViewBillTableModel(billController.getBills(DateUtilities.getMonthBegin(), DateUtilities.getMonthEnd()));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex);
        }
        tbViewBill.setModel(vbtm);
        for (int i = 0; i < tbViewBill.getColumnModel().getColumnCount(); i++) {
            TableColumn tc = tbViewBill.getColumnModel().getColumn(i);
            tc.setCellRenderer(new ViewBillTableRenderer());
        }
        dpFrom.setDate(DateUtilities.getMonthBegin());
        dpSince.setDate(DateUtilities.getMonthEnd());

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pnNorth = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        pnCenter = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        dpFrom = new org.jdesktop.swingx.JXDatePicker();
        dpSince = new org.jdesktop.swingx.JXDatePicker();
        jButton6 = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbViewBill = new javax.swing.JTable();
        pnSouth = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenu4 = new javax.swing.JMenu();
        jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
        jRadioButtonMenuItem2 = new javax.swing.JRadioButtonMenuItem();
        jRadioButtonMenuItem3 = new javax.swing.JRadioButtonMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        miExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        miShowCategories = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Eingaben- Ausgabenrechnung");

        pnNorth.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new java.awt.GridBagLayout());

        jButton1.setText("Neue Rechnung");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onNewBill(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(15, 15, 15, 15);
        jPanel4.add(jButton1, gridBagConstraints);

        pnNorth.add(jPanel4, java.awt.BorderLayout.WEST);

        getContentPane().add(pnNorth, java.awt.BorderLayout.PAGE_START);

        pnCenter.setLayout(new java.awt.BorderLayout());

        jPanel7.setLayout(new java.awt.BorderLayout());

        jPanel8.setLayout(new java.awt.GridBagLayout());

        jLabel2.setText("Rechnungen von:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(15, 15, 15, 15);
        jPanel8.add(jLabel2, gridBagConstraints);

        jLabel1.setText("bis:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(15, 15, 15, 15);
        jPanel8.add(jLabel1, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        jPanel8.add(dpFrom, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        jPanel8.add(dpSince, gridBagConstraints);

        jButton6.setText("Anzeigen");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onShowBills(evt);
            }
        });
        jPanel8.add(jButton6, new java.awt.GridBagConstraints());

        jPanel7.add(jPanel8, java.awt.BorderLayout.WEST);

        pnCenter.add(jPanel7, java.awt.BorderLayout.NORTH);

        jPanel6.setLayout(new java.awt.GridBagLayout());

        tbViewBill.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tbViewBill);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 429;
        gridBagConstraints.ipady = 400;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 15, 5, 15);
        jPanel6.add(jScrollPane1, gridBagConstraints);

        pnCenter.add(jPanel6, java.awt.BorderLayout.CENTER);

        getContentPane().add(pnCenter, java.awt.BorderLayout.CENTER);

        pnSouth.setLayout(new java.awt.BorderLayout());

        jPanel5.setLayout(new java.awt.GridBagLayout());

        jButton3.setText("Bearbeiten");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onEdit(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(15, 15, 15, 15);
        jPanel5.add(jButton3, gridBagConstraints);

        jButton2.setText("Ansehen");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onView(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(15, 15, 15, 15);
        jPanel5.add(jButton2, gridBagConstraints);

        jButton4.setText("Löschen");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onDelete(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(15, 15, 15, 15);
        jPanel5.add(jButton4, gridBagConstraints);

        pnSouth.add(jPanel5, java.awt.BorderLayout.CENTER);

        getContentPane().add(pnSouth, java.awt.BorderLayout.SOUTH);

        jMenu1.setText("Datei");

        jMenuItem5.setText("Neue Rechnung");
        jMenu1.add(jMenuItem5);
        jMenu1.add(jSeparator2);

        jMenu4.setText("Design");

        jRadioButtonMenuItem1.setSelected(true);
        jRadioButtonMenuItem1.setText("Dark Nimbus");
        jMenu4.add(jRadioButtonMenuItem1);

        jRadioButtonMenuItem2.setSelected(true);
        jRadioButtonMenuItem2.setText("Light Nimbus");
        jMenu4.add(jRadioButtonMenuItem2);

        jRadioButtonMenuItem3.setSelected(true);
        jRadioButtonMenuItem3.setText("System Design");
        jMenu4.add(jRadioButtonMenuItem3);

        jMenu1.add(jMenu4);
        jMenu1.add(jSeparator1);

        miExit.setText("Beenden");
        miExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onClose(evt);
            }
        });
        jMenu1.add(miExit);

        jMenuBar2.add(jMenu1);

        jMenu2.setText("Kategorien");

        miShowCategories.setText("Kategorien anzeigen");
        miShowCategories.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onShowCategories(evt);
            }
        });
        jMenu2.add(miShowCategories);

        jMenuBar2.add(jMenu2);

        jMenu3.setText("Rechnungen");

        jMenuItem1.setText("Statistik erzeugen");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createStatistic(evt);
            }
        });
        jMenu3.add(jMenuItem1);

        jMenuItem2.setText("Umsatzsteuervoranmelung erzeugen");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onCreateTOTAR(evt);
            }
        });
        jMenu3.add(jMenuItem2);

        jMenuBar2.add(jMenu3);

        setJMenuBar(jMenuBar2);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Button event to show ShowCategoriesDlg
     *
     * @param evt ButtonEvent
     */
    private void onShowCategories(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onShowCategories
        new ShowCategoriesDlg(this, true).setVisible(true);
    }//GEN-LAST:event_onShowCategories

    /**
     * Button event to call NewBillDlg and add returned bill to billController.
     *
     * @param evt ButtonEvent
     */
    private void onNewBill(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onNewBill
        NewBillDlg nbDlg = new NewBillDlg(null, true, null);
        nbDlg.setVisible(true);
        if (nbDlg.isOk()) {
            Bill b = nbDlg.getBill();
            Timestamp bid = new Timestamp(new java.util.Date().getTime());
            b.setId(bid);
            try {
                billController.addBill(b);
                tbViewBill.updateUI();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex);
            }
        }
    }//GEN-LAST:event_onNewBill

    /**
     * Button event to show bill details of selected bill
     *
     * @param evt ButtonEvent
     */
    private void onView(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onView
        int index = tbViewBill.getSelectedRow();
        if (index >= 0) {
            Bill b = billController.getBill(index);
            ViewBillDlg vbd = new ViewBillDlg(null, true, b);
            vbd.setVisible(true);
        }
    }//GEN-LAST:event_onView

    /**
     * Button event to show bills, which are only within the chosen dates
     *
     * @param evt ButtonEvent
     */
    private void onShowBills(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onShowBills
        Date from = dpFrom.getDate();
        Date since = dpSince.getDate();

        if (from != null && since != null) {
            try {
                billController.updateList(from, since);
                tbViewBill.updateUI();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex);
            }

        }
    }//GEN-LAST:event_onShowBills

    /**
     * Button event to delete selected bill
     *
     * @param evt ButtonEvent
     */
    private void onDelete(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onDelete
        try {
            int index = tbViewBill.getSelectedRow();
            if (index >= 0 && billController.getSize() > 0) {
                Bill b = billController.getBill(index);

                billController.deleteBill(b);
                tbViewBill.updateUI();

            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex);
        }
    }//GEN-LAST:event_onDelete

    /**
     * Button event to edit bill details of selected bill
     *
     * @param evt ButtonEvent
     */
    private void onEdit(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onEdit
        int index = tbViewBill.getSelectedRow();
        if (index >= 0 && billController.getSize() > 0) {
            Bill oldBill = billController.getBill(index);
            NewBillDlg nbDlg = new NewBillDlg(null, true, oldBill);
            nbDlg.setVisible(true);
            if (nbDlg.isOk() && nbDlg.getBill() != null) {
                Bill newBill = nbDlg.getBill();
                newBill.setId(oldBill.getId());
                try {
                    billController.editBill(index, newBill);
                    tbViewBill.updateUI();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, ex);
                }
            }
        }
    }//GEN-LAST:event_onEdit

    /**
     * Button event to call PrintBillDlg which prints several details of
     * selected bills, which are within the chosen dates on a pdf-file
     *
     * @param evt ButtonEvent
     */
    private void createStatistic(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createStatistic
        PrintBillDlg pbDlg = new PrintBillDlg();
        pbDlg.setVisible(true);
    }//GEN-LAST:event_createStatistic

    /**
     * Button event to call CreateTurnOverTaxAdvanceReturnDlg which prints the
     * turnover tax advance return on a pdf-file
     *
     * @param evt ButtonEvent
     */
    private void onCreateTOTAR(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onCreateTOTAR
        CreateTurnOverTaxAdvanceReturnDlg ctotard = new CreateTurnOverTaxAdvanceReturnDlg();
        ctotard.setVisible(true);
    }//GEN-LAST:event_onCreateTOTAR

    /**
     * Stops the database and terminates itself
     *
     * @param evt ButtonEvent
     */
    private void onClose(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onClose
        try {
            Desktop.getDesktop().open(new File("database/stop.bat"));
            Thread.sleep(4000);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex);
        }
        System.exit(0);
    }//GEN-LAST:event_onClose

    /**
     * Check if program was ever launched before. If not request user for UID and Name of the user´s company
     * 
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            PropertyManager pm = PropertyManager.getInstance();
            pm.printProperties();
            if (pm.getValue("uid") == null || pm.getValue("uName") == null) {
                JOptionPane.showMessageDialog(null, "Herzlich Willkommen zum ersten Besuch dieses Programms! \n "
                        + "Im folgenden werden Sie dazu aufgefordert einige Daten Ihres Unternemes einzugeben.");

                String uid = "";
                String uname = "";

                while ((uid == null || uname == null) || (uid.length() <= 0 && uname.length() <= 0)) {
                    uid = JOptionPane.showInputDialog(null, "Bitte geben Sie die UID ein");
                    uname = JOptionPane.showInputDialog(null, "Bitte geben Sie den Namen Ihres Unternehmens ein");
                }

                pm.addProperty("uid", uid);
                pm.addProperty("uName", uname);

            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
        }

        try {
            Runtime.getRuntime().exec("database/start.bat");
            Thread.sleep(5000);
        } catch (Exception ex) {
        }

        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        UIManager.put("nimbusBlueGrey", new Color(85, 85, 85));
        UIManager.put("control", new Color(85, 85, 85));
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainFrame().setVisible(true);
            }
        });

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXDatePicker dpFrom;
    private org.jdesktop.swingx.JXDatePicker dpSince;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem2;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JMenuItem miExit;
    private javax.swing.JMenuItem miShowCategories;
    private javax.swing.JPanel pnCenter;
    private javax.swing.JPanel pnNorth;
    private javax.swing.JPanel pnSouth;
    private javax.swing.JTable tbViewBill;
    // End of variables declaration//GEN-END:variables
}
